package com.ruoyi.fileserver.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.fileserver.domain.SysFile;
import com.ruoyi.fileserver.service.ISysFileService;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 学生管理Controller
 *
 * @author DL
 * @date 2023-12-18
 */
@RestController
@RequestMapping("/sysFile")
public class SysFileController extends BaseController {

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 上传
     */
    @PostMapping("/upload/{module}")
    public AjaxResult upload(@PathVariable("module")String module,@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        String day = DateUtils.datePath2();
        String parentPath = RuoYiConfig.getProfile() + File.separator + module + File.separator + day;
        File parent = new File(parentPath);
        //文件夹不存在则创建
        if (!parent.exists()) {
            parent.mkdirs();
        }
        String srcFileName = file.getOriginalFilename();
        String suffix = srcFileName.substring(srcFileName.lastIndexOf("."));
        String fid = UUID.randomUUID().toString();
        File dest = new File(parentPath, fid + suffix);
        try {
            SysFile sysFile = new SysFile();
            sysFile.setFid(fid);
            sysFile.setFileName(srcFileName);
            sysFile.setSuffix(suffix);
            // 子文件夹名称：分模块+日期
            sysFile.setDay(day);
            sysFile.setModule(module);
            sysFileService.saveSysFile(file, dest, sysFile);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(ExceptionUtils.getStackTrace(e));
        }
        return AjaxResult.success(fid);
    }

    /**
     * 展示图片
     */
    @GetMapping("/show/{fid}")
    public void show(@PathVariable("fid") String fid, HttpServletRequest request, HttpServletResponse response)  throws Exception{
        SysFile sysFile = sysFileService.getSysFile(fid);
        response.setContentType("image/jpeg");
        StringBuilder filePath =  new StringBuilder();
        filePath.append(sysFile.getModule() + File.separator + sysFile.getDay() + File.separator + sysFile.getFid() + sysFile.getSuffix());
        File imgFile = new File(RuoYiConfig.getProfile() + File.separator + filePath);
        responseFile(response, imgFile);
    }

    /**
     * 展示图片
     */
    @GetMapping("/down/{fid}")
    public void down(@PathVariable("fid") String fid, HttpServletResponse response) throws Exception{
        SysFile sysFile = sysFileService.getSysFile(fid);
        // 设置下载的响应头信息
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition
                .attachment()    // 附件形式
                .filename(sysFile.getFileName() + sysFile.getSuffix(), StandardCharsets.UTF_8)  // 文件名称 & 编码
                .build()
                .toString());
        StringBuilder filePath =  new StringBuilder();
        filePath.append(sysFile.getModule() + File.separator + sysFile.getDay() + File.separator + sysFile.getFid() + sysFile.getSuffix());
        File imgFile = new File(RuoYiConfig.getProfile() + File.separator  + filePath);
        responseFile(response, imgFile);
    }

    /**
     * 响应输出图片文件
     * @param response
     * @param imgFile
     */
    private void responseFile(HttpServletResponse response, File imgFile) throws Exception{
            InputStream is = new FileInputStream(imgFile);
            OutputStream os = response.getOutputStream();
            byte [] buffer = new byte[1024];
            while(is.read(buffer) != -1){
                os.write(buffer);
            }
            os.flush();
    }
}
